package com.zxh.springboot.bean;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.io.File;
import java.io.IOException;
import java.util.Properties;


public class SpringApplication {

    private Class<?> mainClass;

    public SpringApplication(Class<?> mainClass) {
        this.mainClass = mainClass;
    }

    public static void run(Class<?> cls,String... args) {
        new SpringApplication(cls).run(args);
    }

    private void run(String[] args){
        //创建容器,并刷新
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(mainClass);
        context.refresh();

        ConfigurableEnvironment environment = context.getEnvironment();

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);
        File tempDir = null;
        try {
            tempDir = createTempDir("Tomcat");
            tomcat.addWebapp("/",tempDir.getAbsolutePath());
            tomcat.start();
            tomcat.getServer().await();
        }catch (LifecycleException e){
            e.printStackTrace();
            return;
        }catch (Exception e){
            e.printStackTrace();
            return;
        }
    }

    File createTempDir(String prefix) throws Exception{
        try {
            File tempDir = File.createTempFile(prefix + ".","."+8080);
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        }catch (IOException e){
            throw new Exception("Unable to create tempDir,java.io.tempDir is set to "+System.getProperty("java.io.tmpdir"),e);
        }
    }
}
